import useThemeStore from '@/store/theme'

export const amapLoadScript = (callback) => {
  const themeStore = useThemeStore()
  const { AmapKey, AmapSecretkey } = themeStore
  const url = `https://webapi.amap.com/maps?v=2.0&key=${AmapKey}`

  const existingScript = document.getElementById(url)
  const cb = callback || function () {}

  if (!existingScript) {
    window._AMapSecurityConfig = {
      securityJsCode: AmapSecretkey
    }

    const script = document.createElement('script')
    script.src = url
    script.id = url
    document.head.appendChild(script)

    script.onload = function () {
      cb(null, script)
    }
    script.onerror = function () {
      cb(new Error('Failed to load ' + url), script)
    }
  } else {
    if (window.AMap && cb) {
      cb(null, existingScript)
    }
  }
}
